const { ccclass, property } = cc._decorator;

enum EState {
    move,
    attack,
    hurt,
    idle,
}
@ccclass
export default class NewClass extends cc.Component {

    @property
    hp: number = 4;

    @property
    speed: number = 100;

    @property
    attackRange: number = 5;

    @property(cc.Node)
    hero: cc.Node = null;


    state: EState = EState.move;
    start() {

    }

    update(dt) {
        this.move();
    }

    //碰撞
    onCollisionEnter(other: cc.Collider, self: cc.Collider) {
        cc.log(other.node.group + ':' + other.tag);
        if (other.node.group == 'hero' && other.tag == 1) {
            let anim = self.node.getComponent(cc.Animation);
            this.hp--;
            if (this.hp > 0) {
                anim.play('enemy_hurt');
            }
            else {
                anim.play('enemy_dead');
                this.getComponent(cc.BoxCollider).enabled = false;
            }
        }
    }

    onDead() {
        this.node.removeFromParent();
    }
    onAttackOver(){
        this.state=EState.idle;
    }

    move() {
        let rigid = this.node.getComponent(cc.RigidBody);
        let lv = rigid.linearVelocity

        let clip: string = null
        let dir = 0;
        let scaleX = Math.abs(this.node.scaleX);

        if(this.state==EState.attack) return;
        
        if (this.hero.x > this.node.x) {
            dir = 1;
            this.node.scaleX = scaleX
        }
        else {
            dir = -1;
            this.node.scaleX = -scaleX
        }

        if (Math.abs(this.hero.x - this.node.x) < this.attackRange) {
            this.playAmian(EState.attack)
            lv.x = 0;
        }
        else {
            //移动
            if (dir) {
                lv.x = dir * this.speed;
            }
            else {
                lv.x = 0;
            }
            this.playAmian(EState.move)

        }
        rigid.linearVelocity = lv;
       
    }

    playAmian(anim: EState) {
        let animation = this.node.getComponent(cc.Animation);
        if (anim == this.state) return;
            
        switch(anim){
            case EState.move:
                animation.play('enemy_move');
            break;
            case EState.hurt:
                animation.play('enemy_hurt');
            break;
            case EState.attack:
                animation.play('enemy_attack');
            break;
        }
        this.state = anim;
    }
}
